<?php

namespace app\api\middleware;

use app\admin\model\Admin;
use app\admin\model\Error;
use think\facade\Config;
use app\admin\model\Token;

/**
 * 登录验证 (适合大部分前端登录验证处理)
 */
class Auth
{

    /**
     * 错误请求名称
     */
    private $cmd = 'app_request';

    /**
     * 检查登录信息
     * @param string $platform 平台名称
     */
    public function check($platform = 'app')
    {
        // 1. 检查 headers 信息
        $get = getallheaders();
        if (isset($get['Authorization'])) {
            // 2. 检查请求次数
            $check = Error::check($this->cmd);
            if (!$check) {
                $auth = $get['Authorization'];
                $token = str_replace('Bearer ', '', $auth);
                file_put_contents('token.txt', $token);
                openssl_private_decrypt(base64_decode($token), $decryptedData, Config::get('xp.private_key'), OPENSSL_PKCS1_OAEP_PADDING);
                if (empty($decryptedData)) {
                    return false;
                }
                [$id, $password, $salt, $salt2, $pushToken, $device] = explode("\t", $decryptedData);
                $user = Admin::find($id);
                if (
                    // 3. 检查用户是否存在
                    $user &&
                    $user->status == 0 &&
                    // 4. 检查密码
                    verifyPassword($user->password, $password, $salt)
                ) {
                    // 5. 检查加密盐
                    $token = Token::where('admin_id', $user->id)->where('platform', $platform)->find();
                    if (
                        $token &&
                        $token->salt == $salt2 &&
                        $token->push == $pushToken &&
                        $token->device == $device
                    ) {
                        return $user;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 处理请求
     */
    public function handle($request, \Closure $next)
    {
        if (!defined('UID')) {
            Error::add($this->cmd);
            return json(['msg' => '未登录或登录已过期，请重新登录！'], 401);
        }
        return $next($request);
    }
}
